<template>
  <div class="bg-background/95 sticky top-0 z-[999] bg-white border-b">
    <!-- pc  header -->
    <!-- pc  header -->
    <!-- pc  header -->
    <!-- {{ categoryList }} -->
    <div class="h-[6rem] lg:block lg:px-4 hidden sticky top-0 z-50 w-full">
      <div class="flex justify-between items-center mx-auto max-w-7xl h-full">
        <div class="flex gap-4 items-center">
          <nuxt-link class="h-[2.88rem] flex-none" :prefetch="false" :to="localePath('/')">
            <img
              class="object-cover flex-none h-full cursor-pointer"
              src="https://cd.sealmg.com/assets/img/logo-img.png"
              alt="SEALMG Logo"
              title="Back to homepage"
              loading="lazy"
            />
          </nuxt-link>
          <!-- FF4E33 -->
          <ClassifyHome v-model="categoryList"></ClassifyHome>
        </div>
        <div class="flex relative gap-6 items-center">
          <div
            class="grid transition-all duration-300 ease-in-out absolute w-full top-[150%]"
            :class="[showSearchD ? 'grid-rows-[1fr] opacity-100 translate-y-0' : 'grid-rows-[0fr] opacity-0 -translate-y-2']"
          >
            <div class="overflow-hidden rounded-[1rem] shadowgg">
              <H5search v-model="input" ref="box" :showSearch="showSearchD" :showSearchD.sync="showSearchD"></H5search>
            </div>
          </div>
          <!-- 输入框   @click="submitSearch"   -->
          <div
            v-if="!isSearchPage"
            class="w-[15rem] h-[2rem] hidden xl:flex bg-[#F7F6F6] rounded-[1.44rem] px-4 gap-3 items-center border border-transparent justify-between has-[:focus]:bg-[#FF4E33]/10 has-[:focus]:border has-[:focus]:border-[#FF4E33]"
          >
            <!-- <div
                class="w-[0.06rem] h-[1rem] border-[0.06rem] border-solid border-[#E4E4E7]"
              ></div> -->
            <input
              autocomplete="off"
              v-model="input"
              @click.stop="handleFocus"
              @keyup.enter="handleKeyUp"
              :placeholder="$t('formPlaceholder.search')"
              type="text"
              class="bg-transparent border-none w-full outline-none placeholder:text-[#D4D4D8] text-sm"
            />
            <span class="el-icon-close cursor-pointer" v-if="input" @click.stop="input = ''"></span>
            <img
              @click.stop="submitSearch"
              src="~/assets/img/mobile/search-icon.png"
              alt="Search icon"
              title="Click to search"
              loading="lazy"
              class="flex-none text-lg h-[1rem] aspect-square cursor-pointer"
            />
          </div>
          <!-- 语言 -->
          <!-- <Langes class="lange-box" langTheme="gray" :showArrow="true" /> -->
          <template v-if="!isSearchPay">
            <!-- /order/cashier -->
            <!-- /order/pay -->
            <Langes></Langes>
          </template>
          <!-- 购物车 -->
          <div v-if="token" @click="userShopcar" class="size-[2rem] bg-[#F7F7F7] rounded-full flex justify-center items-center relative">
            <img
              class="cursor-pointer"
              src="https://cd.sealmg.com/assets/img/mobile/shopcar-icon.png"
              loading="lazy"
              alt="Shopping cart icon"
              title="View your shopping cart"
            />
            <div
              v-if="userInfo.ext && userInfo.ext.cart_num"
              class="border px-[.375rem] py-0 border-white border-solid bg-[#FF4E33] text-[12px] absolute -top-[30%] -right-[35%] text-white rounded-full h-[1.25rem]"
            >
              {{ userInfo.ext.cart_num > 99 ? '99+' : userInfo.ext.cart_num }}
            </div>
          </div>
          <!--用户头像  -->
          <div class="size-[2rem] bg-[#FAFAFA] rounded-full cursor-pointer overflow-hidden" v-if="!token" @click="userLogin()">
            <img :src="avator_img" alt="avator_img" class="object-cover w-full h-full" loading="lazy" />
          </div>
          <!-- 未登录 -->
          <!-- 未登录 -->
          <!-- 未登录 -->
          <el-popover
            v-if="token"
            v-model="visible"
            popper-class="user-popover"
            placement="bottom"
            width="400"
            trigger="click"
            style="border-radius: 16px !important"
          >
            <div class="user-card">
              <div class="base flexbox flex-align-center">
                <img
                  class="avator object-cover flex-none"
                  :src="$globalFn.imgPrefixUrl(userInfo.avatar, 'national_flag')"
                  alt="userInfo.avatar"
                  srcset=""
                />
                <div class="info" @click="userInfoType(1)">
                  <div class="name flexbox flex-align-center">
                    <span class="text line-clamp-1">{{ userInfo.nickname }}</span>
                    <img class="detail" src="https://cd.sealmg.com/assets/img/arrow-right-detail.png" alt="arrow-right-detail" srcset="" />
                  </div>
                  <div class="id">{{ $t('userPanel.userId') }}：{{ userInfo.uid }}</div>
                </div>
              </div>
              <div class="row flexbox flex-align-center flex-justify-between">
                <div class="col" @click="userInfoType('4')">
                  <div class="title one-line capitalize">
                    {{ $t('userPanel.collectNum') }}
                  </div>
                  <div class="num flexbox flex-align-center flex-justify-between">
                    <span class="text">
                      {{ (userInfo.ext && userInfo.ext.collect_num) || 0 }}
                    </span>
                    <img class="icon" src="https://cd.sealmg.com/assets/img/arrow-right-radius.png" alt="arrow-right-radius.png" />
                  </div>
                </div>
                <div class="col" @click="userShopcar">
                  <div class="title one-line capitalize">
                    {{ $t('userPanel.shopcarNum') }}
                  </div>
                  <div class="num flexbox flex-align-center flex-justify-between">
                    <span class="text">{{ (userInfo.ext && userInfo.ext.cart_num) || 0 }}</span>
                    <img class="icon" src="https://cd.sealmg.com/assets/img/arrow-right-radius.png" alt="arrow-right-radius.png" />
                  </div>
                </div>
              </div>
              <div class="item-mode flexbox flex-align-center" @click="userInfoType(1)">
                <img class="icon" src="https://cd.sealmg.com/assets/img/user-account.png" alt="Account icon" title="Account settings" />
                <span class="text capitalize"> {{ $t('userPanel.account') }}</span>
              </div>
              <div class="item-mode flexbox flex-align-center" @click="userInfoType(2)">
                <img
                  class="icon"
                  src="https://cd.sealmg.com/assets/img/user-plane-order.png"
                  alt="https://cd.sealmg.com/assets/img/user-plane-order.png"
                  srcset=""
                />
                <span class="text">{{ $t('userPanel.order') }}</span>
              </div>
              <!-- <div class="item-mode flexbox flex-align-center" @click="userInfoType('trade')">
                                <img class="icon" src="https://cd.sealmg.com/assets/img/user-plane-trade.png" alt="" srcset="">
                                <span class="text">{{$t('userPanel.trade')}}</span>
                            </div> -->
              <div class="item-mode flexbox flex-align-center" @click="userInfoType('3')">
                <img
                  class="icon"
                  src="https://cd.sealmg.com/assets/img/user-plane-cardpwd.png"
                  alt="https://cd.sealmg.com/assets/img/user-plane-cardpwd.png"
                  srcset=""
                />
                <span class="text">{{ $t('userPanel.cardpwd') }}</span>
              </div>
              <div class="item-mode flexbox flex-align-center" @click="userInfoType(4)">
                <img
                  class="icon"
                  src="https://cd.sealmg.com/assets/img/user-plane-collect.png"
                  alt="https://cd.sealmg.com/assets/img/user-plane-collect.png"
                  srcset=""
                />
                <span class="text">{{ $t('userPanel.collect') }}</span>
                 <img
                  src="~/assets/img/discountLabel.png"
                  class="size-4 ml-3"
                  alt="Discount label"
                  title="Product discount"
                  v-if="Number(userInfo?.ext?.collect_max_discount) > 0"
                />
              </div>
              <div class="item-mode flexbox flex-align-center" @click="userInfoType(5)">
                <img
                  class="icon"
                  src="https://cd.sealmg.com/assets/img/user-plane-notice.png"
                  alt="https://cd.sealmg.com/assets/img/user-plane-notice.png"
                  srcset=""
                />
                <span class="text">{{ $t('userPanel.notice') }}</span>
              </div>
              <div class="item-mode flexbox flex-align-center" @click="userLogout">
                <img
                  class="icon"
                  src="https://cd.sealmg.com/assets/img/user-plane-logout.png"
                  alt="https://cd.sealmg.com/assets/img/user-plane-logout.png"
                  srcset=""
                />
                <span class="text">{{ $t('formBtn.logout') }}</span>
              </div>
            </div>
            <div slot="reference" class="size-[2rem] bg-[#FAFAFA] rounded-full overflow-hidden cursor-pointer">
              <img
                class="avatar-img size-full"
                v-if="$globalFn.imgPrefixUrl(userInfo.avatar)"
                :src="$globalFn.imgPrefixUrl(userInfo.avatar)"
                alt="avatar"
                title="avatar"
              />
            </div>
          </el-popover>
        </div>
      </div>
    </div>
    <!-- h5  header -->
    <!-- h5  header -->
    <!-- h5  header -->
    <!-- h5  header -->
    <div class="max-lg:flex hidden flex-col w-full border-b">
      <div class="flex justify-between px-4 py-[.4rem]">
        <nuxt-link :to="localePath('/')" class="h-[2.13rem] ]" :prefetch="false">
          <img
            class="object-cove h-full"
            src="https://cd.sealmg.com/assets/img/logo-img.png"
            alt="https://cd.sealmg.com/assets/img/logo-img.png"
            srcset=""
            loading="lazy"
          />
        </nuxt-link>
        <template v-if="!isSearchPay">
          <!-- /order/cashier -->
          <!-- /order/pay -->
          <Langes></Langes>
        </template>
      </div>
      <div class="flex gap-4 px-4 py-[.4rem] items-center relative justify-between">
        <div
          class="grid transition-all duration-300 ease-in-out lg:top-[150%] top-[100%] max-lg:px-4 max-lg:translate-x-[-50%] max-lg:left-[50%] absolute w-full"
          :class="[showSearchDs ? 'grid-rows-[1fr] opacity-100 translate-y-0' : 'grid-rows-[0fr] opacity-0 -translate-y-2']"
        >
          <div class="shadowgg rounded-[1rem] overflow-hidden">
            <H5searchs v-model="inputs" :showSearch="showSearchDs" ref="box" :showSearchDs.sync="showSearchDs"></H5searchs>
          </div>
        </div>
        <img
          loading="lazy"
          alt="https://cd.sealmg.com/assets/img/mobile/nav-icon.png"
          class="size-[1.5rem] cursor-pointer"
          src="https://cd.sealmg.com/assets/img/mobile/nav-icon.png"
          @click="openthebulletbox"
        />
        <div
          v-if="!currentPath.includes('/search')"
          class="w-full h-[2rem] gap-3 bg-[#F7F7F7] rounded-[1.44rem] px-3 flex items-center border border-transparent justify-between has-[:focus]:bg-[#FF4E33]/10 has-[:focus]:border has-[:focus]:border-[#FF4E33]"
        >
          <input
            autocomplete="off"
            v-model="inputs"
            type="text"
            @click.stop="handleFocuss"
            @keyup.enter="submitSearchs"
            @blur="showSearchDs = false"
            :placeholder="$t('formPlaceholder.search')"
            class="w-[95%] bg-transparent border-none outline-none placeholder:text-[#D4D4D8] text-sm"
          />
           <span class="el-icon-close cursor-pointer" v-if="inputs" @click.stop="inputs = ''"></span>
          <div @click.stop="submitSearchs" class="flex gap-3 items-center cursor-pointer">
            <div class="w-[0.06rem] h-[0.88rem] border-[0.06rem] border-solid border-[#E5E5E5]"></div>
            <i class="el-icon-search text-[#999999] font-bold"></i>
            <!-- <img class="size-6" src="https://cd.sealmg.com/assets/img/search-icon.png" alt="" /> -->
          </div>
        </div>
        <!--用户头像  -->
        <!--用户头像  -->
        <!--用户头像  -->
        <div class="size-[1.5rem] bg-[#FAFAFA] rounded-full cursor-pointer flex-none" v-if="!token" @click="userLogin()">
          <img :src="avator_img" alt="avator_img" class="object-cover w-full h-full" loading="lazy" />
        </div>
        <!-- 未登录 -->
        <!-- 未登录 -->
        <!-- 未登录 -->
        <el-popover
          v-if="token"
          v-model="visiblevisible"
          popper-class="user-popover"
          placement="bottom"
          width="400"
          trigger="click"
          style="border-radius: 16px !important"
        >
          <div class="user-card">
            <div class="base flexbox flex-align-center">
              <img class="avator flex-none" :src="$globalFn.imgPrefixUrl(userInfo.avatar)" :alt="userInfo.avatar" srcset="" />
              <div class="info" @click="userInfoType(1)">
                <div class="name flexbox flex-align-center">
                  <span class="text line-clamp-1">{{ userInfo.nickname }}</span>
                  <img
                    class="detail"
                    src="https://cd.sealmg.com/assets/img/arrow-right-detail.png"
                    alt="https://cd.sealmg.com/assets/img/arrow-right-detail.png"
                    srcset=""
                  />
                </div>
                <div class="id">{{ $t('userPanel.userId') }}：{{ userInfo.uid }}</div>
              </div>
            </div>
            <div class="row flexbox flex-align-center flex-justify-between">
              <div class="col" @click="userInfoType(4)">
                <div class="title one-line">
                  {{ $t('userPanel.collectNum') }}
                </div>
                <div class="num flexbox flex-align-center flex-justify-between">
                  <span class="text">{{ (userInfo.ext && userInfo.ext.collect_num) || 0 }}</span>
                  <img
                    class="icon"
                    src="https://cd.sealmg.com/assets/img/arrow-right-radius.png"
                    alt="https://cd.sealmg.com/assets/img/arrow-right-radius.png"
                  />
                </div>
              </div>
              <div class="col" @click="userShopcar">
                <div class="title one-line">
                  {{ $t('userPanel.shopcarNum') }}
                </div>
                <div class="num flexbox flex-align-center flex-justify-between">
                  <span class="text">{{ (userInfo.ext && userInfo.ext.cart_num) || 0 }}</span>
                  <img
                    class="icon"
                    src="https://cd.sealmg.com/assets/img/arrow-right-radius.png"
                    alt="https://cd.sealmg.com/assets/img/arrow-right-radius.png"
                  />
                </div>
              </div>
            </div>
            <div class="item-mode flexbox flex-align-center" @click="userInfoType(1)">
              <img
                class="icon"
                src="https://cd.sealmg.com/assets/img/user-account.png"
                alt="https://cd.sealmg.com/assets/img/user-account.png"
                srcset=""
              />
              <span class="text">{{ $t('userPanel.account') }}</span>
            </div>
            <div class="item-mode flexbox flex-align-center" @click="userInfoType(2)">
              <img
                class="icon"
                src="https://cd.sealmg.com/assets/img/user-plane-order.png"
                alt="https://cd.sealmg.com/assets/img/user-plane-order.png"
                srcset=""
              />
              <span class="text">{{ $t('userPanel.order') }}</span>
            </div>
            <!-- <div class="item-mode flexbox flex-align-center" @click="userInfoType('trade')">
                                <img class="icon" src="https://cd.sealmg.com/assets/img/user-plane-trade.png" alt="" srcset="">
                                <span class="text">{{$t('userPanel.trade')}}</span>
                            </div> -->
            <div class="item-mode flexbox flex-align-center" @click="userInfoType(3)">
              <img
                class="icon"
                src="https://cd.sealmg.com/assets/img/user-plane-cardpwd.png"
                alt="https://cd.sealmg.com/assets/img/user-plane-cardpwd.png"
                srcset=""
              />
              <span class="text">{{ $t('userPanel.cardpwd') }}</span>
            </div>
            <div class="item-mode flexbox flex-align-center" @click="userInfoType(4)">
              <img
                class="icon"
                src="https://cd.sealmg.com/assets/img/user-plane-collect.png"
                alt="https://cd.sealmg.com/assets/img/user-plane-collect.png"
                srcset=""
              />
              <span class="text">{{ $t('userPanel.collect') }}</span>
               <img
                src="~/assets/img/discountLabel.png"
                class="size-4 ml-3"
                alt="Discount label"
                title="Product discount"
                v-if="Number(userInfo?.ext?.collect_max_discount) > 0"
              />
            </div>
            <div class="item-mode flexbox flex-align-center" @click="userInfoType(5)">
              <img
                class="icon"
                src="https://cd.sealmg.com/assets/img/user-plane-notice.png"
                alt="https://cd.sealmg.com/assets/img/user-plane-notice.png"
                srcset=""
              />
              <span class="text">{{ $t('userPanel.notice') }}</span>
            </div>
            <div class="item-mode flexbox flex-align-center" @click="userLogout">
              <img
                class="icon"
                src="https://cd.sealmg.com/assets/img/user-plane-logout.png"
                alt="https://cd.sealmg.com/assets/img/user-plane-logout.png"
                srcset=""
              />
              <span class="text">{{ $t('formBtn.logout') }}</span>
            </div>
          </div>
          <div slot="reference" class="size-[1.5rem] bg-[#FAFAFA] rounded-full overflow-hidden cursor-pointer">
            <img
              class="avatar-img size-full"
              v-if="$globalFn.imgPrefixUrl(userInfo.avatar)"
              :src="$globalFn.imgPrefixUrl(userInfo.avatar)"
              :alt="userInfo.avatar"
              srcset=""
            />
          </div>
        </el-popover>
      </div>
    </div>
    <ClassifyHomeH5 v-model="categoryList" :showDrawer="showDrawer" :showDrawers.sync="showDrawer"></ClassifyHomeH5>
  </div>
</template>
<script>
  let avator_img = 'https://cd.sealmg.com/assets/img/avator-img.png'
  export default {
    components: {},
    data() {
      return {
        visible: false, // 用户面板显示状态(PC)
        visiblevisible: false, // 用户面板显示状态(移动端)
        showDrawer: false, // 移动端导航抽屉显示状态
        avator_img: avator_img, // 默认头像图片
        input: '', // 搜索输入框内容(PC)
        activeIndex: '0', // 当前激活的导航项索引
        showSearchD: false, // 搜索框展开状态(PC)
        showSearchDs: false, // 搜索框展开状态(移动端)
        inputs: '' // 搜索输入框内容(移动端)
        // categoryList: [], // 用于存储本地分类数据
      }
    },
    computed: {
      // 获取用户token,优先从cookie获取,其次从vuex获取
      token() {
        const user = this.$store.state.user
        return this.$cookies.get('token') || user?.token || ''
      },
      // 获取当前路由路径,用于导航高亮
      currentPath() {
        return this.$route.path
      },
      // 获取用户信息,从vuex中获取,用于显示用户面板
      userInfo() {
        const user = this.$store.state.user
        return user?.userInfo || {}
      },
      // 获取商品分类列表,从vuex中获取,用于显示导航菜单
      categoryList() {
        return this.$store.state.initData?.goodsCategory || []
      },
      // 判断当前是否是搜索页面
      isSearchPage() {
        return this.$route.path.includes('/search')
      },
      // 判断当前是否是支付页面
      isSearchPay() {
        return this.$route.path.includes('/order/cashier') || this.$route.path.includes('/order/pay')
      }
    },
    created() {
      // this.getCategoryData();
      if (process.client) {
        // document.addEventListener("keyup", this.handleKeyUp);
        // 在组件挂载时添加全局点击事件监听器
        document.addEventListener('click', this.handleClickOutside)
      }
    },
    beforeDestroy() {
      // 组件销毁前移除全局键盘事件监听
      // document.removeEventListener("keyup", this.handleKeyUp);
      document.removeEventListener('click', this.handleClickOutside)
    },
    methods: {
      clears() {
        this.input = ''
      },
      async getCategoryData() {
        try {
          const res = await this.$axios.get(`/api/goods_category/index`)
          this.categoryList = res
        } catch (error) {
          console.error('获取分类数据失败:', error)
        }
      },
      goHomepage() {
        this.showDrawer = false
        this.$router.push({
          path: this.localePath('/')
        })
      },
      handleFocuss() {
        this.showSearchDs = true
      },
      handleClickOutside(event) {
        this.showSearchD = false
        this.showSearchDs = false
      },
      handleFocus() {
        this.showSearchD = true
      },
      openthebulletbox() {
        this.showDrawer = !this.showDrawer
      },
      handleKeyUp(event) {
        if (!this.input.trim().length) return

        if (event.key == 'Enter') {
          this.submitSearch()
        }
      },
      showSearch() {
        return this.currentPath && this.currentPath.lastIndexOf('/search') > -1 ? false : true
      },
      // nvaActive(item) {
      //   let locale = this.$i18n.locale;
      //   if (item) {
      //     if (locale == "en") {
      //       return item.path == this.currentPath;
      //     } else {
      //       if (item.path == "/" && item.path + locale == this.currentPath) {
      //         return true;
      //       }
      //       return "/" + locale + item.path == this.currentPath;
      //     }
      //   } else {
      //     return false;
      //   }
      // },
      submitSearch(value) {
        if (!this.input.trim().length) return

        this.showSearchD = false
        this.showSearchDs = false

        this.addNewItems()
        setTimeout(() => {
          this.input = ''
        }, 300)
        this.$router.push({
          path: this.localePath('/search'),
          query: {
            keywords: this.input
          }
        })
      },
      submitSearchs(value) {
        if (!this.inputs.trim().length) return
        this.showSearchD = false

        this.showSearchDs = false
        this.addNewItemss()
        setTimeout(() => {
          this.inputs = ''
        }, 300)
        this.$router.push({
          path: this.localePath('/search'),
          query: {
            keywords: this.inputs
          }
        })
      },
      addNewItemss() {
        const newItems = [this.inputs]
        const history = JSON.parse(localStorage.getItem('history')) || []
        let updatedHistory = [...history, ...newItems]
        // 检查数组长度，如果超过 6 个元素，移除最早添加的元素
        if (updatedHistory.length > 6) {
          updatedHistory = updatedHistory.slice(-6)
        }
        localStorage.setItem('history', JSON.stringify(updatedHistory))
      },
      // 存入历史
      addNewItems() {
        const newItems = [this.input]
        const history = JSON.parse(localStorage.getItem('history')) || []
        let updatedHistory = [...history, ...newItems]
        // 检查数组长度，如果超过 6 个元素，移除最早添加的元素
        if (updatedHistory.length > 6) {
          updatedHistory = updatedHistory.slice(-6)
        }
        localStorage.setItem('history', JSON.stringify(updatedHistory))
      },
      userLogout() {
        this.$store.dispatch('user/userLogout')
        this.visible = false
        this.visiblevisible = false
      },
      goNavPage(item) {
        // this.showDrawer = false;
        // 判断是否新闻进行重开窗口d
        let p = this.localePath(item.route.path)
        return p
      },
      goNavPages(item) {
        this.showDrawer = false
        // 判断是否新闻进行重开窗口d
        let path = this.localePath(item.route.path)
        this.$router.push({ path })
      },
      // 用户登录跳转路由方法
      userLogin() {
        let currentUrl = window.location.href
        this.$router.push({
          path: this.localePath('/login'),
          query: { redirect: currentUrl }
        })
      },
      // 用户面板跳转路由方法
      userInfoType(key) {
        const routeMap = {
          1: '/user/account',
          2: '/user/order',
          3: '/user/cardpwd',
          4: '/user/collect',
          5: '/user/notice'
        }
        this.$router.push({
          path: this.localePath(routeMap[key]),
          query: { type: key }
        })
        this.visible = false
        this.visiblevisible = false
      },
      // 用户购物车点击事件处理
      userShopcar() {
        this.$router.push({
          path: this.localePath('/shop-cart')
        })
        this.visible = false
        this.visiblevisible = false
      }
    }
  }
</script>
<style lang="less" scoped>
  .nav-drawer {
    z-index: 2000 !important;
    /deep/ .el-drawer {
      width: 304px !important;
    }
  }
  /deep/ .el-popover,
  .el-popper,
  .user-popover {
    border-radius: 16px !important;
  }
</style>
